<template lang="pug">
  .CreateAccountModal
    Modal(
      v-model="isShowInvoiceInstantModal"
      :title="createInvoiceModalTitle"
      class-name="vertical-center-modal"
      width="80%"
    )
      .h500.overflow-y-scroll(:class="modalKey != 'createModal' && modalKey != 'editModal' ? 'has-disabled' : ''")
        Form.ivu-row.has-rules-item2.ivu-form-basic(ref="formData" :model="formData" :rules="setRules" :label-width="120")
          FormItem.form-item.ivu-col(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-show="item.isShow")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="modalKey != 'createModal' ? '未填写' : item.placeholder" :disabled="item.isDisabled" clearable)
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="modalKey != 'createModal' ? '未填写' : item.placeholder" filterable :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
              Select(v-else v-model="formData[item.model]" :placeholder="modalKey != 'createModal' ? '未填写' : item.placeholder" filterable :disabled="item.isDisabled")
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-if="item.fn" v-model="formData[item.model]" :placeholder="modalKey != 'createModal' ? '未填写' : item.placeholder" :clearable="false" :type="item.mode ? item.mode : 'date'" :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
              DatePicker.w-100(v-else v-model="formData[item.model]" :placeholder="modalKey != 'createModal' ? '未填写' : item.placeholder" :clearable="false" :type="item.mode ? item.mode : 'date'" :disabled="item.isDisabled")
            template(v-if="item.type === 'switch'")
              i-switch(v-model="formData[item.model]")
        
        Divider
          Icon.text-gray-ccc(type="md-cut")

        Form(ref="tableData")
          Row.form-item.mb-10
            Col.text-left.font-14.pl-25(v-for="(title, titleIndex) of thead" :key="titleIndex" :span="title.span") {{title.txt}}
          Row.form-item.mb-10(v-for="(row, rowIndex) of tableData" :key="rowIndex")
            Col.pl-10.pr-10(span="6")
              Input(v-model="row.productDetail" disabled)
            //- Col.pl-10.pr-10(span="4")
            //-   Input(v-model="row.billAmt" disabled)
            Col.pl-10.pr-10(span="6")
              Input(v-model="row.taxRate" disabled)
            Col.pl-5.pr-10(span="6")
              Select(v-model="row.invoiceTaxName" :disabled="modalKey === 'lookModal'")
                Option(v-for="(c_item, c_index) of row.invoiceTaxNames" :key="c_index" :value="c_item") {{c_item}}
            Col.pl-10.pr-10(span="6")
              Input.w-100(v-model="row.amt" @on-blur="(val) => handleChangeAmt(val, rowIndex)" :disabled="modalKey === 'lookModal'")
            //- Col.pl-10.pr-10(span="4")
            //-   Input(v-model="row.restAmt" disabled)
          //- FormItem.form-item.ivu-col(v-for="(item, index) of tableData" :key="index" :prop="item.prop")

      .clearfix(slot="footer" v-if="this.modalKey !== 'createModal'")
        Button(type="text" @click="cancel") 取消
        Button(v-show="!(modalKey == 'lookModal')" type="primary" @click="handleSubmit" :loading="!isCanSubmit") 保存
      .clearfix(slot="footer" v-if="this.modalKey === 'createModal'")
        Button(type="text" @click="cancel") 取消
        Button(v-show="!(modalKey == 'lookModal')" type="primary" @click="handleSubmit" :loading="!isCanSubmit") 保存并关闭
        Button(v-show="!(modalKey == 'lookModal')" type="primary" @click="handleSubmit" data-type="goOn" :loading="!isCanSubmit") 保存并继续添加
</template>

<script>
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { FinanceApi } from '@/api/Finance.api.js'
import { FinanceInvoiceApi } from '@/api/FinanceInvoice.api.js'
import { InvoiceInstantThead } from '../tableHead'

export default {
  name: 'InvoiceInstantModal',

  watch: {
  },

  computed: {
    setFormItem () {
      if (this.modalKey === 'createModal') {
        this.formItem.map(item => {
          if (['companyInfos', 'billType', 'periodYM', 'invoiceDate', 'remark', 'invoiceNo'].indexOf(item.model) !== -1) {
            item.isDisabled = false
            item.style = 'ivu-col-span-8 is-required'
          } else {
            item.style = 'ivu-col-span-8 remove-required'
          }
          if (['invoiceNo', 'oldInvoiceNo', 'returnReason', 'redInvoiceNo'].indexOf(item.model) !== -1) {
            item.isShow = false
          }
          if (['legalName', 'creditCode'].indexOf(item.model) !== -1) {
            item.style = 'ivu-col-span-8 is-required'
          }
        })
      } else if (this.modalKey === 'editModal') {
        this.formItem.map(item => {
          if (['remark'].indexOf(item.model) !== -1) {
            item.isDisabled = false
            item.style = 'ivu-col-span-8 is-required'
          } else {
            item.isDisabled = true
            item.style = 'ivu-col-span-8 remove-required'
          }
          if (['invoiceNo', 'oldInvoiceNo', 'returnReason', 'redInvoiceNo'].indexOf(item.model) !== -1) {
            item.isShow = false
          }
        })
      } else if (this.modalKey === 'replaceModal') {
        this.formItem.map(item => {
          if (['returnReason', 'redInvoiceNo'].indexOf(item.model) !== -1) {
            item.isDisabled = false
            item.style = 'ivu-col-span-8 is-required'
          } else {
            item.isDisabled = true
            item.style = 'ivu-col-span-8 remove-required'
          }

          if (['redInvoiceNo'].indexOf(item.model) !== -1) {
            item.isShow = false
          } else {
            item.isShow = true
          }
          // item.isShow = true
        })
      } else if (this.modalKey === 'lookModal') {
        this.formItem.map(item => {
          item.isDisabled = true
          item.isShow = true
          item.style = 'ivu-col-span-8 remove-required'
        })
      }
      return this.formItem
    },

    setRules () {
      if (this.modalKey == 'createModal') {
        return this.rules
      } else if (this.modalKey == 'editModal') {
        return this.rulesEdit
      } else if (this.modalKey == 'replaceModal') {
        return this.rulesReplace
      } else {
        return {}
      }
    }
  },

  data () {
    return {
      isShowInvoiceInstantModal: false,
      modalKey: 'createModal',
      createInvoiceModalTitle: null,
      isCanSubmit: true,
      // thead: _cloneDeep(InvoiceInstantThead),
      // thead: ['产品明细', '账单金额', '税率', '税目', '开票金额'],
      thead: [
        {txt: '产品明细', span: 6},
        // {txt: '账单金额', span: 4},
        {txt: '税率', span: 6},
        {txt: '税目', span: 6},
        {txt: '开票金额', span: 6},
      ],
      tableData: [],
      tableComone: {
        pageIndex: 1,
        totalRows: 0,
        pageSize: 10
      },
      formData: {
        invoiceChannel: '1',
        companyInfos: null,
        billType: 'HRO',
        periodYM: new Date(),
        productType: null,
        legalName: null,
        invoiceType: null,
        creditCode: null,
        address: null,
        phone: null,
        bankName: null,
        bankNo: null,
        invoiceReceiver: null,
        phoneNo: null,
        email: null,
        invoiceDate: new Date(),
        remark: null,
        totalAmt: null,

        // 用不着，但又需要传的
        invoiceID: '',
        parentName: '',
        parentID: '',
        totalAmt: 0,
        invoiceManner: null,
        invoiceNo: null,
        oldInvoiceNo: null,
        returnReason: null,
        redInvoiceNo: null,
      },
      formItem: [
        { type: 'select', label: '开票渠道：', placeholder: '请选择开票渠道', prop: 'invoiceChannel', model: 'invoiceChannel', style: 'ivu-col-span-8', options: 'invoiceChannelOps', isDisabled: true, isShow: true },
        { type: 'select', label: '客户名称：', placeholder: '请选择客户名称', prop: 'companyInfos', model: 'companyInfos', style: 'ivu-col-span-8', options: 'childrenCompanys', fn: 'companyInfosChange', isDisabled: false, isShow: true },
        { type: 'select', label: '应收账单：', placeholder: '请选择应收账单', prop: 'billType', model: 'billType', style: 'ivu-col-span-8', options: 'billTypeList', isDisabled: false, isShow: true },
        { type: 'datePicker', label: '费用月份：', placeholder: '请选择费用月份', prop: 'periodYM', model: 'periodYM', style: 'ivu-col-span-8', mode: 'month', fn: 'periodChange', isDisabled: false, isShow: true },
        { type: 'input', label: '产品类别：', placeholder: '请输入产品类别', prop: 'productType', model: 'productType', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '名称：', placeholder: '请输入名称', prop: 'legalName', model: 'legalName', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'select', label: '发票类型：', placeholder: '请选择发票类型', prop: 'invoiceType', model: 'invoiceType', style: 'ivu-col-span-8', options: 'invoiceTypeList', fn: 'invoiceTypeChange', isDisabled: false, isShow: true },
        { type: 'input', label: '纳税人识别号：', placeholder: '请输入纳税人识别号', prop: 'creditCode', model: 'creditCode', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '地址：', placeholder: '请输入地址', prop: 'address', model: 'address', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '电话：', placeholder: '请输入电话', prop: 'phone', model: 'phone', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '开户行：', placeholder: '请输入开户行', prop: 'bankName', model: 'bankName', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '银行账号：', placeholder: '请输入银行账号', prop: 'bankNo', model: 'bankNo', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '发票接收人：', placeholder: '请输入发票接收人', prop: 'invoiceReceiver', model: 'invoiceReceiver', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8', isDisabled: true, isShow: true },
        { type: 'input', label: '手机号码：', placeholder: '请输入手机号码', prop: 'phoneNo', model: 'phoneNo', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8', isDisabled: true, isShow: true },
        { type: 'input', label: '邮箱：', placeholder: '请输入邮箱', prop: 'email', model: 'email', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8', isDisabled: true, isShow: true },
        { type: 'datePicker', label: '申请开票日期：', placeholder: '请选择申请开票日期', prop: 'invoiceDate', model: 'invoiceDate', style: 'ivu-col-span-8', mode: 'date', fn: 'periodChange', isDisabled: false, isShow: true },
        { type: 'input', label: '申请开票说明：', placeholder: '请输入申请开票说明', prop: 'remark', model: 'remark', style: 'ivu-col-span-8', isDisabled: false, isShow: true },
        { type: 'input', label: '开票金额：', placeholder: '请输入开票金额', prop: 'totalAmt', model: 'totalAmt', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '发票号码：', placeholder: '请输入发票号码', prop: 'invoiceNo', model: 'invoiceNo', style: 'ivu-col-span-8', isDisabled: false, isShow: true },
        // { type: 'input', label: '原开票：', placeholder: '请输入原开票', prop: 'oldInvoiceNo', model: 'oldInvoiceNo', style: 'ivu-col-span-8', isDisabled: true, isShow: true },
        { type: 'input', label: '退换票原因：', placeholder: '请输入退换票原因', prop: 'returnReason', model: 'returnReason', style: 'ivu-col-span-8', isDisabled: false, isShow: true },
        // { type: 'input', label: '红字发票：', placeholder: '请输入红字发票', prop: 'redInvoiceNo', model: 'redInvoiceNo', style: 'ivu-col-span-8', isDisabled: true, isShow: false },
      ],
      rules: {
        companyInfos: [
          { required: true, message: '请选择客户名称', trigger: 'change' }
        ],
        billType: [
          { required: true, message: '请选择应收账单', trigger: 'change' }
        ],
        legalName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        invoiceType: [
          { required: true, message: '请选择发票类型', trigger: 'change' }
        ],
        creditCode: [
          { required: true, message: '请输入纳税人识别号', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'change' }
        ],
        bankName: [
          { required: true, message: '请输入开户行', trigger: 'change' }
        ],
        bankNo: [
          { required: true, message: '请输入银行账号', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入申请开票说明', trigger: 'blur' }
        ],
        phoneNo: [
          // { required: true, message: '请输入手机号码', trigger: 'change' },
          { type: 'string', message: '请输入11位数的手机号码', pattern: /^\d{11}$/ }
        ],
        email: [
          // { required: true, message: '请输入邮箱', trigger: 'change' },
          { type: 'string', message: '请输入正确的邮箱', pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ }
        ]
      },
      rulesEdit: {
        legalName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        invoiceType: [
          { required: true, message: '请选择发票类型', trigger: 'change' }
        ],
        creditCode: [
          { required: true, message: '请输入纳税人识别号', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'change' }
        ],
        bankName: [
          { required: true, message: '请输入开户行', trigger: 'change' }
        ],
        bankNo: [
          { required: true, message: '请输入银行账号', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入开票说明', trigger: 'blur' }
        ],
        phoneNo: [
          // { required: true, message: '请输入手机号码', trigger: 'change' },
          { type: 'string', message: '请输入11位数的手机号码', pattern: /^\d{11}$/ }
        ],
        email: [
          // { required: true, message: '请输入邮箱', trigger: 'change' },
          { type: 'string', message: '请输入正确的邮箱', pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ }
        ]
      },
      rulesReplace: {
        returnReason: [
          { required: true, message: '请输入退换票原因', trigger: 'blur' }
        ]
      },
      arrListDown: {
        // parentCompanys: [],
        childrenCompanys: [],
        status: [],
        billTypeList: [{ label: 'HRO', value: 'HRO' }],
        invoiceTypeList: [
          { label: '增值税专用发票', value: '增值税专用发票' },
          { label: '增值税普通发票', value: '增值税普通发票' },
          { label: '电子发票-普票', value: '电子发票-普票' },
        ],
        invoiceChannelOps: [
          { label: '账单开票', value: '0' },
          { label: '即时开票', value: '1' },
        ],
        // legalNameList: [],
        // legalNameListInit: [], // 法人原始下拉列表
      },
      // selectedParentCompany: {}, // 选中的集团
      selectedCompanyInfo: null, // 选中的客户
      selectedLegal: null, // 选中的法人
    }
  },

  mounted () {
    this.getChildCompanys()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    cancel () {
      this.isShowInvoiceInstantModal = false
    },

    show () {
      this.selectedCompanyInfo = null // 选中的客户清空
      this.selectedLegal = null // 选中的法人清空

      // this.arrListDown.childrenCompanys = [] // 客户下拉清空
      // this.arrListDown.legalNameList = [] // 法人下拉清空

      this.isCanSubmit = true
      this.isShowInvoiceInstantModal = true
      this.$refs.formData.resetFields({})
      this.tableData = []
      console.log('点击是的show()')
      console.log('this.formData: ', this.formData)
      console.log('this.$refs.formData: ', this.$refs.formData)
      console.log('this.selectedCompanyInfo: ', this.selectedCompanyInfo)
    },

    // 获取客户名称下拉-1
    async getChildCompanys () {
      let resp = await FinanceApi.getChildCompanys()
      var arr = []
      console.log('获取客户名称下拉: ', resp)
      if (resp.status == 200 && resp.data.success) {
        resp.data.data.map(item => {
          if (item.group == 'customer') {
            item.items.map(c_item => {
              arr.push({label: c_item.value, value: c_item.key})
            })
          }
        })
        this.arrListDown.childrenCompanys = arr
      }
    },

    // 客户名称选择改变-2
    companyInfosChange (model, event) {
      console.log('客户名称选择改变 model: ', model, ', event: ', event)
      if (event && event.length) {
        this.selectedCompanyInfo = this.arrListDown.childrenCompanys.find(item => {return item.value == event})
        console.log('选中的客户 this.selectedCompanyInfo: ', this.selectedCompanyInfo)
        this.getAddResponse()
      } else {
        // this.selectedLegal = null
        this.formData.companyInfos = []
      }
    },

    // 费用月份选择改变
    periodChange (model, event) {
      console.log('费用月份选择改变 model: ', model, ', event: ', event)
      if (model === 'periodYM') {
        this.formData[model] = this.$moment(event).format('YYYY-MM')
        this.getAddResponse()
      } else {
        this.formData[model] = this.$moment(event).format('YYYY-MM-DD')
      }
    },

    // 获取发票申请数据
    getAddResponse () {
      var companyInfos = [{CompanyID: this.selectedCompanyInfo.value, CompanyName: this.selectedCompanyInfo.label}]
      if (this.modalKey === 'createModal' && this.formData.periodYM && this.formData.billType && this.formData.companyInfos) {
        var params = {
          ParentID: '',
          ParentName: '',
          CompanyInfos: companyInfos,
          PeriodYear: this.$moment(this.formData.periodYM).format('YYYY'),
          PeriodMonth: this.$moment(this.formData.periodYM).format('MM'),
          BillType: this.formData.billType,
        }
        console.log('❤ params: ', params)

        FinanceInvoiceApi.getForthwithAddResponse(params).then(resp => {
          console.log('获取发票申请数据: ', resp)
          // 客户名称为多选时，开票金额=账单金额且禁用
          if (resp.status == 200 && resp.data.success) {
            var result = resp.data.data
            var totalAmt = 0

            // 初始默认税目
            result.details.map(row => {
              totalAmt += row.amt
              // row.restAmt = (row.billAmt - row.invoiceAmt).toFixed(2) // 剩余金额=账单金额-已开票金额
              if (row.invoiceTaxNames.length) {
                row.invoiceTaxName = row.invoiceTaxNames[0]
              }
            })
            this.tableData = result.details

            // 默认法人名称
            this.selectedLegal = result.legalInfos[0]
            if(this.selectedLegal){
              Object.keys(this.selectedLegal).forEach(key => {
                if(key!=='invoiceChannel'){
                  this.formData[key] = this.selectedLegal[key]
                }

              })
            }
            // 相应赋值
            this.formData.productType = result.productType // 产品类别
            this.formData.remark = result.remark // 开票说明
            // this.formData.invoiceChannel = result.invoiceChannel+'' // 开票渠道
            // this.formData.restAmt = 0 // 开票金额
            this.invoiceTypeChange('invoiceType', this.formData.invoiceType)

            setTimeout(() => {
              this.formData.totalAmt = 0
            });
          } else {
            this.$Message.error(resp.data.message)

            this.tableData = []
            // this.legalNameListInit = []
            // this.arrListDown.legalNameList = []

            this.formData.legalName = null

            // 清空相应赋值
            Object.keys(this.formData).forEach(key => {
              var tempArr = ['parentID', 'companyInfos', 'billType', 'periodYM', 'invoiceType', 'remark','invoiceChannel']
              if (tempArr.indexOf(key) < 0) {
                this.formData[key] = ''
              }
            })
          }
        })
      }
    },

    // 表格里的剩余开票金额输入改变
    handleChangeAmt (val, rowIndex) {
      this.formData.totalAmt = 0
      // this.formData.restAmt = 0
      this.tableData.map(row => {
        this.formData.totalAmt += +row.amt
        // this.formData.restAmt += +row.amt
      })
      this.formData.totalAmt = this.formData.totalAmt.toFixed(2)
      // this.formData.restAmt = this.formData.restAmt.toFixed(2)
    },

    // 根据ID获取信息
    async getModel (id) {
      this.arrListDown.childrenCompanys = []
      var params = {
        InvoiceID: id
      }
      let resp = null
      if (this.modalKey === 'editModal') {
        resp = await FinanceInvoiceApi.getInvoice(params)
      } else if (this.modalKey === 'replaceModal') {
        resp = await FinanceInvoiceApi.getReplaceResponse(params)
      } else if (this.modalKey === 'lookModal') {
        resp = await FinanceInvoiceApi.getInvoiceInfo(params)
      }

      if (resp.status === 200 && resp.data.success) {
        this.show()
        var result = resp.data.data

        // 表格处理
        var restAmtTotal = 0
        result.details.map(row => {
          restAmtTotal += row.restAmt
          
          row.restAmt = row.restAmt.toFixed(2)
          if (row.invoiceTaxNames.length) {
            row.invoiceTaxName = row.invoiceTaxNames[0]
          }
        })
        this.tableData = result.details

        // 默认法人名称
        this.selectedLegal = result.legalInfos[0]
        if (this.selectedLegal){
          Object.keys(this.selectedLegal).forEach(key => {
            this.formData[key] = this.selectedLegal[key]
          })
        }
        

        // 相应赋值
        Object.keys(this.formData).forEach(key => {
          var tempArr = ['periodYM', 'companyInfos', 'legalName']
          if (tempArr.indexOf(key) < 0) {
            this.formData[key] = result[key]
          }
        })
        // this.formData.invoiceChannel = result.invoiceChannel + ''

        // 申请开票日期
        this.formData.invoiceDate = this.$moment(result.invoiceDate).format('YYYY-MM-DD')

        // 费用月份
        var periodMonth = +result.periodMonth < 10 ? '0' + result.periodMonth : result.periodMonth
        this.formData.periodYM = result.periodYear + '-' + periodMonth

        this.selectedParentCompany = {value: result.parentID, label: result.parentName}

        // // 客户名称 
        // this.formData.companyInfos = result.companyInfos.map(item => {return item.companyID})

        // 法人名称
        // var tempLegal = {}
        if (result.creditCode) {
          this.selectedLegal = result.legalInfos.find(item => {return item.creditCode === result.creditCode})
          // console.log('☆☆ this.selectedLegal: ', this.selectedLegal)
          // this.formData.legalName = this.selectedLegal.creditCode
          // var tempLegal = {label: this.selectedLegal.legalName, value: this.selectedLegal.creditCode}
          // this.formData.legalName = tempLegal
          
        }

        // 客户名称
        this.selectedCompanyInfo = []
        result.companyInfos.map(item => {
          this.selectedCompanyInfo.push({value: item.companyID, label: item.companyName}) // 选中的客户=接口返回的
          this.arrListDown.childrenCompanys.push({value: item.companyID, label: item.companyName})
        })

        // 待开票金额
        this.formData.restAmt = ['lookModal', 'replaceModal'].indexOf(this.modalKey) != -1 ? result.restAmt : restAmtTotal.toFixed(2)
        console.log('☆☆☆this.formData.restAmt: ', this.formData.restAmt)

        setTimeout(() => {
          // 客户名称 
          this.formData.companyInfos = result.companyInfos.map(item => {return item.companyID})
          this.formData.phoneNo = this.selectedLegal.phoneNo ? this.selectedLegal.phoneNo : null
          this.formData.email = this.selectedLegal.email ? this.selectedLegal.email : null
          this.formData.invoiceReceiver = this.selectedLegal.invoiceReceiver ? this.selectedLegal.invoiceReceiver : null
        });
      } else {
        this.$Message.error({
          content: resp.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 提交表单
    handleSubmit (e) {
      console.log('☆ this.formData: ', this.formData)
      var companyInfos = []
      if (this.selectedCompanyInfo) {
        companyInfos = [{CompanyID: this.selectedCompanyInfo.value, CompanyName: this.selectedCompanyInfo.label}]
      }
      var params = {
        ...this.formData,
        oldInvoiceNo: this.formData.invoiceID,
        PeriodYear: this.$moment(this.formData.periodYM).format('YYYY'),
        PeriodMonth: this.$moment(this.formData.periodYM).format('MM'),
        companyInfos: companyInfos,
        Details: this.tableData,
      }
      console.log('提交表单 params:', params)
      var amtArr = []
      this.tableData.map(item => {
        if (item.amt < 0) {
          amtArr.push(item.amt)
        }
      })
      console.log('this.tableData: ', this.tableData)
      console.log('amtArr: ', amtArr)
      if (this.modalKey === 'createModal') {
        this.formData.returnReason = ' '
        this.$refs.formData.validate((valid) => {
          if (valid && companyInfos.length) {
            if (amtArr.length) {
              this.$Message.warning('开票金额不允许输入负数')
            } else if (this.formData.totalAmt == 0) {
              this.$Message.warning('开票金额不允许为0')
            } else {
              this.isCanSubmit = false
              FinanceInvoiceApi.addForthwithFinanceInvoice(params).then(resp=>{
                console.log('新建-提交表单 resp:', resp)
                if (resp.data.success) {
                  this.$Message.success(resp.data.message)
                  this.isShowInvoiceInstantModal = e.target.innerHTML=='保存并继续添加'
                  this.$emit('query')
                  if (e.target.innerHTML=='保存并继续添加') {
                    this.getAddResponse()
                    this.formData.remark = ''
                    this.isCanSubmit = true
                  }
                } else {
                  this.isCanSubmit = true
                  this.$Message.error(resp.data.message)
                }
              })
            }
          } else {
            this.isCanSubmit = true
            this.$Message.warning('请返回检查必填选项是否输入完整！')
          }
        })
      } else if (this.modalKey === 'editModal') {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            if (amtArr.length) {
              this.$Message.warning('开票金额不允许输入负数')
            } else if (this.formData.totalAmt == 0) {
              this.$Message.warning('开票金额不允许为0')
            } else {
              this.isCanSubmit = false
              
              FinanceInvoiceApi.editFinanceInvoice(params).then(resp=>{
                console.log('编辑-提交表单 resp:', resp)
                if (resp.data.success) {
                  this.$Message.success(resp.data.message)
                  this.isShowInvoiceInstantModal = false
                  this.$emit('query')
                } else {
                  this.isCanSubmit = true
                  this.$Message.error(resp.data.message)
                }
              })
            }
          } else {
            this.isCanSubmit = true
            this.$Message.warning('请返回检查必填选项是否输入完整！')
          }
        })
      } else if (this.modalKey === 'replaceModal') {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.isCanSubmit = false
            FinanceInvoiceApi.replaceFinanceInvoice(params).then(resp=>{
              console.log('退换票-提交表单 resp:', resp)
              if (resp.data.success) {
                this.$Message.success(resp.data.message)
                this.isShowInvoiceInstantModal = false
                this.$emit('query')
              } else {
                this.isCanSubmit = true
                this.$Message.error(resp.data.message)
              }
            })
          }
        })
      }
    },

    // 发票类型改变
    invoiceTypeChange (model, value) {
      if (value) {
        console.log('发票类型改变 model: ', model, ', value: ', value)
        console.log('this.formData.invoiceType: ', this.formData.invoiceType)
        console.log('this.formData.invoiceType: ', this.formData.invoiceType)
        if (this.formData.invoiceType == '增值税专用发票') {
          console.log('❤ 6项 必填')
          this.formItem.map(item => {
            if (['creditCode', 'address', 'phone', 'bankName', 'bankNo'].indexOf(item.model) !== -1) {
              item.style = 'ivu-col-span-8 is-required'
              if (this.selectedLegal) {
                this.formData[item.model] = this.selectedLegal[item.model] && this.selectedLegal[item.model] != '' ? this.selectedLegal[item.model] : null
              } else {
                this.formData[item.model] = '-'
              }
            }

            if (['invoiceReceiver', 'phoneNo', 'email'].indexOf(item.model) !== -1) {
              item.style = 'ivu-col-span-8 remove-required'
            }
          })
        } else if (this.formData.invoiceType == '电子发票-普票') {
          this.formItem.map(item => {
            if (['creditCode', 'address', 'phone', 'bankName', 'bankNo'].indexOf(item.model) !== -1) {
              item.style = 'ivu-col-span-8 remove-required'
              if (this.selectedLegal) {
                this.formData[item.model] = this.selectedLegal[item.model] && this.selectedLegal[item.model] != '' ? this.selectedLegal[item.model] : '-'
              } else {
                this.formData[item.model] = '-'
              }
            }

            if (['legalName', 'creditCode', 'invoiceReceiver', 'phoneNo', 'email'].indexOf(item.model) !== -1) {
              item.style = 'ivu-col-span-8 is-required'
            }
          })
        } else {
          console.log('☆ 只有2项 必填')
          this.formItem.map(item => {
            if (['creditCode', 'address', 'phone', 'bankName', 'bankNo', 'invoiceReceiver', 'phoneNo', 'email'].indexOf(item.model) !== -1) {
              item.style = 'ivu-col-span-8 remove-required'
              if (this.selectedLegal) {
                this.formData[item.model] = this.selectedLegal[item.model] && this.selectedLegal[item.model] != '' ? this.selectedLegal[item.model] : '-'
              } else {
                this.formData[item.model] = '-'
              }
            }
            if (['legalName', 'creditCode'].indexOf(item.model) !== -1) {
              item.style = 'ivu-col-span-8 is-required'
            }
          })
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
